const Service = require("egg").Service;
const dayjs = require("dayjs");
const idGenerateUtil = require("@jianghujs/jianghu/app/common/idGenerateUtil");
const _ = require("lodash");
const { ORDER_STATUS, DATE_FORMAT } = require("../constant/constant");
const validateUtil = require("@jianghujs/jianghu/app/common/validateUtil");
const { BizError, ERROR_INFO_ENUM } = require("../constant/error");
const actionDataScheme = Object.freeze({
	contractToOrder: {
		type: "object",
		additionalProperties: true,
		required: ["customerId", "carId"],
		properties: {
			customerId: { type: "string" },
			carId: { type: "string" },
		},
	},
	runningAccountToOrder: {
		type: "object",
		additionalProperties: true,
		required: ["ticketContentRequest", "contractId"],
		properties: {
			ticketContentRequest: { type: "string" },
			contractId: { type: "string" },
		},
	},
});
class ToOrderService extends Service {
	// 生成合同表时同步到订单表
	async contractToOrder(actionData) {
		validateUtil.validate(actionDataScheme.contractToOrder, actionData);
		const { jianghuKnex } = this.app;
		const { ctx } = this;
		const { userId, username } = ctx.userInfo;
		const { customerId, contractId, carNumber, carId, rentAmount, serviceCharge, depositAmount } = actionData;
		const payableAmount = Number(rentAmount) + Number(serviceCharge);
		const idSequence = _.padStart(
			await idGenerateUtil.idPlus({
				knex: this.app.jianghuKnex,
				tableName: "order",
				columnName: "idSequence",
			}),
			3,
			0
		);
		const orderData = {
			deposit: depositAmount,
			orderId: contractId,
			customerId,
			carNumber,
			idSequence,
			// FIXME:未计入服务费
			payableAmount: isNaN(rentAmount) ? 0 : rentAmount,
		};
		await jianghuKnex.transaction(async trx => {
			await Promise.all([
				trx("contract").jhInsert(actionData, ctx),
				trx("order").jhInsert(
					{
						...orderData,
						operationByUserId: userId,
						operationByUser: username,
					},
					ctx
				),
				trx("order").where({ carId }).jhUpdate({ status: "已签约" }, ctx),
				trx("basic").where({ carId }).jhUpdate({ operationStatus: "不可用", notOperationReason: "已签约" }, ctx),
			]);
		});
	}
	// 处理收付申请，处理抽屉点击保存时调用该方法,actionData为runningAccount表的字段
	async runningAccountToOrder(actionData) {
		validateUtil.validate(actionDataScheme.runningAccountToOrder, actionData);
		const { jianghuKnex, knex } = this.app;
		const { ctx } = this;
		const { flowAmount, contractId, flowType, ticketContentRequest, ticketId } = actionData;
		let tempAmount = flowAmount;
		const orderItem = await knex("order").where({ contractId }).first();
		const orderStatus = orderItem.status;
		let status = "";
		let requestItems = ticketContentRequest ? JSON.parse(ticketContentRequest) : [];
		for (let row of requestItems) {
			if (row.requestType === "押金") {
				if (flowType === "收款申请") {
					tempAmount -= row.requestAmount;
					status = ORDER_STATUS.PAY_DEPOSIT;
				} else if (flowType === "付款申请") {
					tempAmount = 0;
					if (orderStatus !== ORDER_STATUS.INSPECTED) {
						throw new BizError(ERROR_INFO_ENUM.NOT_INSPECTED);
					}
					status = ORDER_STATUS.PAY_DEPOSIT_BACK;
				}
				break;
			}
		}
		const updatedOrderData = {
			paidAmount: parseFloat(orderItem.paidAmount) + parseFloat(tempAmount),
			paymentDate: new dayjs().format(DATE_FORMAT),
			status: status !== "" ? status : orderItem.status,
		};
		await jianghuKnex.transaction(async trx => {
			await trx("order").where({ contractId }).jhUpdate(updatedOrderData, ctx);
		});
	}
}
module.exports = ToOrderService;
